package com.yuyang.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuyang.common.constant.ProductConstants;
import com.yuyang.common.utils.PageUtils;
import com.yuyang.common.utils.Query;
import com.yuyang.gulimall.product.dao.CategoryDao;
import com.yuyang.gulimall.product.entity.CategoryEntity;
import com.yuyang.gulimall.product.service.CategoryBrandRelationService;
import com.yuyang.gulimall.product.service.CategoryService;
import com.yuyang.gulimall.product.vo.Catelog2Vo;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    RedissonClient redissonClient;
    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }


    public List<CategoryEntity> listWithTree() {
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        //找到所有的一级分类
        List<CategoryEntity> level1Menus = categoryEntities.stream().
                filter(item -> item.getCatLevel() == 1).
                map(menu -> {
                    //找到所有的子分类
                    menu.setChildren(getChildrens(menu, categoryEntities));
                    return menu;
                }).sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort()))).collect(Collectors.toList());


        return level1Menus;
    }


    public List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {

        List<CategoryEntity> childrens = all.stream().
                filter(item -> Objects.equals(item.getParentCid(), root.getCatId())).
                peek(item -> item.setChildren(getChildrens(item, all))).
                sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort()))).collect(Collectors.toList());

        return childrens;
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> pathList = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, pathList);
        Collections.reverse(pathList);

        return pathList.toArray(new Long[parentPath.size()]);
    }
//    同时进行多种缓存操作
//    @Caching(evict = {
//            @CacheEvict(value = {"category"}, key = "'getCatelogLevelOne'"),
//            @CacheEvict(value = {"category"}, key = "'getCatelogLevelTwo'"),
//    }
//    )
    @CacheEvict(value = "category", allEntries = true) //更新数据库数据后删除所有分区的缓存
    @Transactional
    @Override
    public void updateCascade(CategoryEntity categoryEntity) {
        RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("product:category:RWlock");
        RLock rLock = readWriteLock.writeLock();
        try {
            rLock.lock();
            this.updateById(categoryEntity);
            categoryBrandRelationService.updateCategory(categoryEntity.getCatId(), categoryEntity.getName());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            rLock.unlock();
        }
        //同时修改缓存中的数据
        //删除缓存,等待下一次主动查询进行更新

    }

    /**
     * Spring-Cache的不足之处：
     *  1）、读模式
     *      缓存穿透：查询一个null数据。解决方案：缓存空数据
     *      缓存击穿：大量并发进来同时查询一个正好过期的数据。解决方案：加锁 ? 默认是无加锁的;使用sync = true来解决击穿问题
     *      缓存雪崩：大量的key同时过期。解决：加随机时间。加上过期时间
     *  2)、写模式：（缓存与数据库一致）
     *      1）、读写加锁。
     *      2）、引入Canal,感知到MySQL的更新去更新Redis
     *      3）、读多写多，直接去数据库查询就行
     *
     *  总结：
     *      常规数据（读多写少，即时性，一致性要求不高的数据，完全可以使用Spring-Cache）：写模式(只要缓存的数据有过期时间就足够了)
     *      特殊数据：特殊设计
     */
    //默认是无加锁的;使用sync = true来解决击穿问题
    @Cacheable(value = {"category"}, key = "#root.methodName", sync = true)
    @Override
    public List<CategoryEntity> getCatelogLevelOne() {

        return this.list(new LambdaQueryWrapper<CategoryEntity>().eq(CategoryEntity::getParentCid, 0));
    }
    //本地锁只能锁住当前线程 分布式情况下需要分布式锁

    public Map<String, List<Catelog2Vo>> getCatelogLevelTwoFromDBWithLocalLock() {
        synchronized (this) {
            return getDataFromDB();
        }
    }

    @Cacheable(value = "catogory", key = "#root.methodName", sync = true)
    @Override
    public Map<String, List<Catelog2Vo>> getCatelogLevelTwo() {
        List<CategoryEntity> all = this.list();
        List<CategoryEntity> catelogLevelOne = getChildrensByParentCId(all, 0L);
        Map<String, List<Catelog2Vo>> collect = catelogLevelOne.stream().collect(Collectors.toMap(levelOne -> levelOne.getCatId().toString(), levelOne -> {
            //封装一级分类的子分类
            Long levelOneCatId = levelOne.getCatId();

            //查找二级分类
            List<CategoryEntity> catelogLevelTwo = getChildrensByParentCId(all, levelOneCatId);
            List<Catelog2Vo> catelog2Vos = null;
            if (catelogLevelTwo != null) {

                catelog2Vos = catelogLevelTwo.stream().map(levelTwo -> {
                    Long levelTwoCatId = levelTwo.getCatId();
                    List<CategoryEntity> catelogLevelThree = getChildrensByParentCId(all, levelTwoCatId);
                    List<Catelog2Vo.Category3Vo> category3Vos = null;
                    if (catelogLevelThree != null) {
                        //封装三级分类
                        category3Vos = catelogLevelThree.stream().map(levelThree ->
                                        new Catelog2Vo.Category3Vo(levelTwoCatId.toString(), levelThree.getCatId().toString(), levelThree.getName())).
                                collect(Collectors.toList());
                    }
                    return new Catelog2Vo(levelOneCatId.toString(), category3Vos, levelTwoCatId.toString(), levelTwo.getName());
                }).collect(Collectors.toList());
            }
            return catelog2Vos;
        }));
        return collect;
    }

    /**
     * 1、缓存穿透：频繁访问数据库中不存再的值 缓存一个空值设置短暂的过期时间
     * 2、缓存雪崩：缓存的数据在某一时刻同时失效 原有的失效时间基础上增加一个随机值
     * 3、缓存击穿：一个热点key失效，被超高并发地访问 加锁
     */

    public Map<String, List<Catelog2Vo>> getCatelogLevelTwoFromDBWithRedisLock() {
        String uuid = UUID.randomUUID().toString();
        //获取分布式锁 设置过期时间防止服务宕机没有删除锁造成死锁
        Boolean lock = stringRedisTemplate.opsForValue().setIfAbsent("lock", uuid, 10L, TimeUnit.SECONDS);
        if (lock) {
            //获取成功后查询数据库
            System.out.println("获取锁成功");
            Map<String, List<Catelog2Vo>> dataFromDB;
            try {
                dataFromDB = getDataFromDB();
                //删除锁 获取值对比是否是自己的锁再删除 需要原子操作
            } finally {
                //业务异常返回时删除锁
                String lua = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
                stringRedisTemplate.execute(new DefaultRedisScript<>(lua, Long.class), Arrays.asList("lock"), uuid);

//            if (uuid.equals(stringRedisTemplate.opsForValue().get("lock"))){
                //删除我自己的锁
//                stringRedisTemplate.delete("lock");
//            }
            }
            return dataFromDB;
        } else {
            System.out.println("获取锁失败重试。。。");
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return getCatelogLevelTwoFromDBWithRedisLock(); //自旋方式
        }
    }

    //Redisson的分布式锁

    public Map<String, List<Catelog2Vo>> getCatelogLevelTwoFromDBWithRedissionLock() {
        //锁的粒度 具体缓存的商品数据 越细越快
        RLock lock = redissonClient.getLock(ProductConstants.PRODUCT_CATELOG_LOCK);
        lock.lock();
        Map<String, List<Catelog2Vo>> dataFromDB = null;
        try {
            dataFromDB = getDataFromDB();
        } finally {
            lock.unlock();
        }
        return dataFromDB;
    }


    public Map<String, List<Catelog2Vo>> getCatelogLevelTwoWithLock() {
        String jsonString = stringRedisTemplate.opsForValue().get(ProductConstants.PRODUCT_CATELOGLEVELTWO);

        if (StringUtils.isEmpty(jsonString)) {

            Map<String, List<Catelog2Vo>> catelogLevelTwoFromDB = getCatelogLevelTwoFromDBWithRedissionLock();

            return catelogLevelTwoFromDB;
        }
        Map<String, List<Catelog2Vo>> stringListMap = JSON.parseObject(jsonString, new TypeReference<Map<String, List<Catelog2Vo>>>() {
        });
        return stringListMap;
    }

    public Map<String, List<Catelog2Vo>> getDataFromDB() {
        //获取锁时重新查询缓存 是否更新
        String jsonString = stringRedisTemplate.opsForValue().get(ProductConstants.PRODUCT_CATELOGLEVELTWO);
        if (StringUtils.isNotEmpty(jsonString)) {
            Map<String, List<Catelog2Vo>> stringListMap = JSON.parseObject(jsonString, new TypeReference<Map<String, List<Catelog2Vo>>>() {
            });
            return stringListMap;
        }
        System.out.println("缓存不命中...查询数据库");
        List<CategoryEntity> all = this.list();
        List<CategoryEntity> catelogLevelOne = getChildrensByParentCId(all, 0L);
        Map<String, List<Catelog2Vo>> collect = catelogLevelOne.stream().collect(Collectors.toMap(levelOne -> levelOne.getCatId().toString(), levelOne -> {
            //封装一级分类的子分类
            Long levelOneCatId = levelOne.getCatId();

            //查找二级分类
            List<CategoryEntity> catelogLevelTwo = getChildrensByParentCId(all, levelOneCatId);
            List<Catelog2Vo> catelog2Vos = null;
            if (catelogLevelTwo != null) {

                catelog2Vos = catelogLevelTwo.stream().map(levelTwo -> {
                    Long levelTwoCatId = levelTwo.getCatId();
                    List<CategoryEntity> catelogLevelThree = getChildrensByParentCId(all, levelTwoCatId);
                    List<Catelog2Vo.Category3Vo> category3Vos = null;
                    if (catelogLevelThree != null) {
                        //封装三级分类
                        category3Vos = catelogLevelThree.stream().map(levelThree ->
                                        new Catelog2Vo.Category3Vo(levelTwoCatId.toString(), levelThree.getCatId().toString(), levelThree.getName())).
                                collect(Collectors.toList());
                    }
                    return new Catelog2Vo(levelOneCatId.toString(), category3Vos, levelTwoCatId.toString(), levelTwo.getName());
                }).collect(Collectors.toList());
            }
            return catelog2Vos;
        }));
        //更新缓存
        stringRedisTemplate.opsForValue().set(ProductConstants.PRODUCT_CATELOGLEVELTWO, JSON.toJSONString(collect), 1L, TimeUnit.DAYS);
        return collect;
    }

    public List<CategoryEntity> getChildrensByParentCId(List<CategoryEntity> all, Long parentCId) {
        return all.stream().filter(item -> item.getParentCid() == parentCId).collect(Collectors.toList());
    }

    private List<Long> findParentPath(Long catelogId, List<Long> pathList) {
        pathList.add(catelogId);
        CategoryEntity categoryEntity = this.getById(catelogId);
        if (categoryEntity.getParentCid() != 0) {
            findParentPath(categoryEntity.getParentCid(), pathList);
        }
        return pathList;
    }

}